define(["../common"], function() {

	var hideData = $.parseJSON($("#hideData").html());

	var num = 0;
	var total = 0;
	var isCancel = false;
	var localVersion = null;
	var defOption = {
		onStart: zeroProgress,
		onFinish: updateVersion
	};
	
	// 实现兼容,让IE下可以跨域请求
	$.ajaxSetup({crossDomain: true});
	
	$("#checkTip").html("正在检查您的离线版本...");
	checkVersion();
	
	// 提交
	$("#syncBubmitBt").click(function() {
		if ($(document).doing(true)) {
			$("<div>").showMsg("当前有操作在执行！", 'error');
			return;
		}
		if (!localVersion.storeId) {
			$(document).showMsg("本地没有任何数据！请先更新", 'error');
			return;
		} else if (localVersion.storeId !== hideData.storeId) {
			$(document).showMsg("当前店铺与本地店铺信息不一致！", 'error');
			return;
		}
		submitData(defOption);
		
	});
	
	// 更新
	$("#syncUpdateBt").click(function() {
		if ($(document).doing(true)) {
			$("<div>").showMsg("当前有操作在执行！", 'error');
			return;
		}
		if (localVersion.storeId && localVersion.storeId !== hideData.storeId) {
			$(document).showMsg("当前店铺与本地店铺信息不一致！", 'error');
			return;
		}
		updateData(defOption);
	});
	
	// 提交并更新
	$("#syncSuUpBt").click(function() {
		if ($(document).doing(true)) {
			$("<div>").showMsg("当前有操作在执行！", 'error');
			return;
		}
		if (!localVersion.storeId) {
			$(document).showMsg("本地没有任何数据！请先更新", 'error');
			return;
		} else if (localVersion.storeId !== hideData.storeId) {
			$(document).showMsg("当前店铺与本地店铺信息不一致！", 'error');
			return;
		}
		submitAndUpdate(defOption);
	});
	
	// 清空并更新
	$("#syncClUpBt").click(function() {
		if ($(document).doing(true)) {
			$("<div>").showMsg("当前有操作在执行！", 'error');
			return;
		}
		if (!localVersion.storeId) {
			updateData(defOption);
			return;
		}
		
		var msgConfig = {
			type: 'confirm',
			content: "确定要清空本地所有数据吗？",
			title: "提示",
			onClose: function() {
				if (!this.val()) {
					$(document).doing(false);
					return;
				}
				clearAndUpdate({
					onStart: zeroProgress,
					onFinish: function() {
						updateVersion(true);
					}
				});
			}
		};
		loadjs(["msgbox"], function() {
			$.msgbox(msgConfig);
		});
	});
	
	// 停止同步
	$("#syncCancelBt").click(function() {
		isCancel = true;
	});
	
	function checkVersion() {
		$.ajax({
			type: "post",
			dataType: "json",
			timeout: 2000,
			url: "http://localhost/sync/getVersion/json?r=" + Math.random(), // 实现兼容: r=Math.random()
			success: function(data) {
				$.ajaxSetup({timeout: null});
				var lv = localVersion = data.result;
				
				if (!localVersion.storeId) {					
					localVersion.syncTime = -1;
					askingToUpdateData();
					
				} else {
					var syncTime = new Date();
					syncTime.setTime(lv.syncTime);
					$("#localStoreName").html(lv.storeName);
					$("#localSyncTime").html(syncTime.format("yyyy-MM-dd hh:mm:ss"));
					$("#localSyncMember").html(lv.syncMember);
					if (lv.reset == true && lv.resetVersion != lv.warVersion) {
						askingToSubmitAClearAUpdateData();
					}
				}
				
				$("#uninstall").hide();
				$("#install").show();
				$("#envVersion").html(lv.envVersion);
				$("#warVersion").html(lv.warVersion);
				showVersion();
				
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				$.ajaxSetup({timeout: null});
				$("#checkTip").html("未检测到您本地的离线版本，请确认已经安装并运行着");
				setTimeout(checkVersion, 20000);
			}
		});
	}
	
	function askingToUpdateData() {
		var msgConfig = {
			type: 'confirm',
			content: "您本地的离线销售版本还没有任何数据，<br>是否现在从服务器上更新下来？",
			title: "提示",
			onClose: function() {
				if (this.val()) {
					updateData(defOption);
				}
			}
		};
		loadjs(["msgbox"], function() {
			$.msgbox(msgConfig);
		});
	}
	
	function askingToSubmitAClearAUpdateData() {
		var msgConfig = {
			type: 'confirm',
			content: "您本地的离线版本需要重置一次数据，<br>是否现在开始？",
			title: "提示",
			onClose: function() {
				if (this.val()) {
					submitAndClearAndUpdateData({
						onStart: zeroProgress,
						onFinish: function() {
							updateVersion(true);
						}
					});
				}
			}
		};
		loadjs(["msgbox"], function() {
			$.msgbox(msgConfig);
		});
	}
	
	// 显示版本信息
	function showVersion() {
		
		var isNew = compareVersion($("#nenvVersion").html(), localVersion.envVersion);
		if (isNew) {
			// 显示ENV新的版本号
			$("#nenvVersion").parent("span").show();
			return;
		} 
		
		// 显示WAR版本信息
		$("#war").show();
		
		isNew = compareVersion($("#nwarVersion").html(), localVersion.warVersion);
		if (isNew) {
			// 显示WAR新的版本号
			$("#nwarVersion").parent("span").show();
		} 
	}
	
	// 版本号比较
	function compareVersion(newVerStr, curVerStr) {
		var newVer = newVerStr.split(".");
		var curVer = curVerStr.split(".");
		var isNew = false;
		for (var i in curVer) {
			if (!curVer[i] || parseInt(newVer[i]) > parseInt(curVer[i])) {
				isNew = true;
				break;
			}
		}
		if (!isNew && newVer.length > curVer.length) {
			isNew = true;
		}
		return isNew;
	}
	
	// 提交
	function submitData(option) {
		var opt = {
			onStart: option.onStart ? option.onStart : function() {},
			onFinish: option.onFinish ? option.onFinish : function() {}
		}
		opt.onStart();
		
		$("#progText").html("准备提交...");
		sumitSale({
			nowPage: 1,
			onStart: zeroProgress,
			onFinish: opt.onFinish
		});
	}
	
	// 提交销售单
	function sumitSale(option) {
		var opt = {
			nowPage: option.nowPage ? option.nowPage : 1,
			onStart: option.onStart ? option.onStart : function() {},
			onFinish: option.onFinish ? option.onFinish : function(){}
		}
		if (isCancel) {
			hideProgress();
			return;
		}
		opt.onStart();
		
		$("#progText").html("提交销售记录...");
		$.getJSON("http://localhost/sync/listSale4Submit/json",{pageNumber: opt.nowPage - 1}, function(data) {
			// data -> pageable
			var result = data.result;
			total = result.totalElements;
			var list = result.content;
			if (!list) {
				setProgress(1, 1, opt.onFinish);
				return;
			}
			
			for (var i in list) {
				sumibt_(list[i], opt);
			}
		
			if (opt.nowPage < result.totalPages) {
				opt.nowPage += 1;
				opt.onStart = null;
				sumitSale(opt);
			}
		}); 
		
		function sumibt_(sale, opt) {
			var params = {
				"localSales": [sale]
			};
			$.ajax({ 
				url: g_shopDomain + "/order/add4SyncDo/json",
				contentType: 'application/json',
				type: 'post',
				dataType: 'json',
				data: JSON.stringify(params), 
				success: function(data) {
					if (data.status !== 0) {
						$("body").append(data.message + "<br>");
						return;
					}
					$.post("http://localhost/sync/delSaleDo/json", {serialCode: sale.serialCode});
					num++;
					setProgress(num, total, opt.onFinish);
				}
			});
		}
	}
	
	// 更新
	function updateData(option) {
		var opt = {
			onStart: option.onStart ? option.onStart : function() {},
			onFinish: option.onFinish ? option.onFinish : function() {}
		}
		opt.onStart();
		
		$("#progText").html("准备更新...");
		updateStoreMember({
			nowPage: 1,
			onStart: zeroProgress,
			onFinish: function() {
				updateStoreGoods({
					nowPage: 1,
					onStart: zeroProgress,
					onFinish: opt.onFinish
				});
			}
		});
	}
	
	// 更新店铺管理员
	function updateStoreMember(option) {
		var opt = {
			nowPage: option.nowPage ? option.nowPage : 1,
			onStart: option.onStart ? option.onStart : function() {},
			onFinish: option.onFinish ? option.onFinish : function() {}
		};
		if (isCancel) {
			hideProgress();
			return;
		}
		opt.onStart();
		
		$("#progText").html("更新管理员信息...");
		$.getJSON(g_shopDomain + "/storeMember/list4Sync/json",{updateTime: localVersion.syncTime, nowPage: opt.nowPage}, function(data) {
			var pi = data.pageInfo;
			var list = data.result;
			total = pi.totalResult;
			if (!list) {
				setProgress(1, 1, opt.onFinish);
				return;
			}
			for (var i in list) {
				$.ajax({ 
					url: "http://localhost/sync/updateStoreMemberDo/json",
					contentType: 'application/json',
					type: 'post',
					dataType: 'json',
					data: JSON.stringify(list[i]), 
					success: function(data) {
						num++;
						setProgress(num, total, opt.onFinish);
					}
				});
			}
			if (opt.nowPage < pi.totalPage) {
				opt.nowPage += 1;
				opt.onStart = null;
				updateStoreMember(opt);
			}
		})
	}
	
	// 更新店铺商品
	function updateStoreGoods(option) {
		var opt = {
			nowPage: option.nowPage ? option.nowPage : 1,
			onStart: option.onStart ? option.onStart : function() {},
			onFinish: option.onFinish ? option.onFinish : function() {}
		};
		if (isCancel) {
			hideProgress();
			return;
		}
		opt.onStart();
		
		$("#progText").html("更新店铺商品信息...");
		$.getJSON(g_shopDomain + "/storeGoods/list4Sync/json",{updateTime: localVersion.syncTime, nowPage: opt.nowPage}, function(data) {
			var pi = data.pageInfo;
			var list = data.result;
			total = pi.totalResult;
			if (!list) {
				setProgress(1, 1, opt.onFinish);
				return;
			}
			for (var i in list) {
				$.post("http://localhost/sync/updateStoreGoodsDo/json",list[i], function(data) {
					num++;
					setProgress(num, total, opt.onFinish);
				});
			}
			if (opt.nowPage < pi.totalPage) {
				opt.nowPage += 1;
				opt.onStart = null;
				updateStoreGoods(opt);
			}
		})
	}
	
	// 清空数据
	function clearData(option) {
		var opt = {
			onStart: option.onStart ? option.onStart : function() {},
			onFinish: option.onFinish ? option.onFinish : function() {}
		}
		opt.onStart();
		
		$("#progText").html("清空数据...");
		$.getJSON("http://localhost/sync/clearDataDo/json",{}, function(data) {
			//...
			$("#localStoreName").empty();
			$("#localSyncTime").empty();
			$("#localSyncMember").empty();
			localVersion.syncTime = -1;
			//num++;
			//setProgress(num, total, opt.onFinish);
			setProgress(1, 1, opt.onFinish);
		}); 
	}
	
	// 提交并更新
	function submitAndUpdate(option) {
		var opt = {
			onStart: option.onStart ? option.onStart : function() {},
			onFinish: option.onFinish ? option.onFinish : function() {}
		}
		opt.onStart();
		
		$("#progText").html("准备提交并更新...");
		submitData({
			onStart: zeroProgress,
			onFinish: function() {
				updateData({
					onStart: zeroProgress,
					onFinish: opt.onFinish
				});
			}
		});
	}
	
	// 清空并更新
	function clearAndUpdate(option) {
		var opt = {
			onStart: option.onStart ? option.onStart : function() {},
			onFinish: option.onFinish ? option.onFinish : function() {}
		}
		opt.onStart();
		
		$("#progText").html("准备清空并更新...");
		clearData({
			onStart: zeroProgress,
			onFinish: function() {
				updateData({
					onStart: zeroProgress,
					onFinish: opt.onFinish
				});
			}
		});
	}
	
	// 提交、清空、更新
	function submitAndClearAndUpdateData(option) {
		var opt = {
			onStart: option.onStart ? option.onStart : function() {},
			onFinish: option.onFinish ? option.onFinish : function() {}
		}
		opt.onStart();
		
		$("#progText").html("准备开始重置数据...");
		submitData({
			onStart: zeroProgress,
			onFinish: function() {
				clearAndUpdate({
					onStart: zeroProgress,
					onFinish: opt.onFinish
				});
			}
		});
	}
	
	// 更新版本(数据类型)信息
	function updateVersion(isReset) {
		var version = {
			storeId: hideData.storeId,
			storeName: hideData.storeName,
			syncMember: hideData.memberName,
			resetVersion: isReset ? localVersion.warVersion : null
		};
		$.post("http://localhost/sync/updateVersionDo/json", version, function(){
			hideProgress();
			checkVersion();
		});
	}
	
	// 关闭进度
	function hideProgress() {
		$("#prog").hide();
		$("#sync").show();
		$("#progPercent").html("0%");
		$("#progBar").width("0%");
		$(document).doing(false);
	}
	
	// 进度置0
	function zeroProgress() {
		num = 0;
		total = 0;
		isCancel = false;
		$("#progPercent").html("0%");
		$("#progBar").width("0%");
		$("#sync").hide();
		$("#prog").show();
		$(document).doing(false);
	}
	
	// 更新进度
	function setProgress(num, total, onFinish) {
		if (isCancel) {
			hideProgress();
			return;
		}
		var percent = (num / total* 100).toFixed(0) + "%";
		$("#progPercent").html(percent);
		$("#progBar").css("width", percent);
		if (percent === "100%") {
			setTimeout(onFinish,1000);
		}
	}
	
});
